package com.itlong.cloud.sdk.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.sdk.CloudTalkSDKDeviceMediaBindDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudTalkSDKMediaSaveOrUpdateDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.SmartCommunityEnum;
import com.itlong.cloud.property.dao.IDeviceMediaPadFaceDao;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.sdk.dao.ICloudTalkSDKMediaDao;
import com.itlong.cloud.sdk.service.ICloudTalkSDKMediaService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      云对讲SDK多媒体资源服务接口实现类
 * <desc/>
 *
 * @createDate 2018/05/22
 */
@Service
public class CloudTalkSDKMediaServiceImpl implements ICloudTalkSDKMediaService {

    @Autowired
    private ICloudTalkSDKMediaDao iCloudTalkSDKMediaDao;

    @Autowired
    private MessageSender messageSender;

    @Autowired
    private IDeviceMediaPadFaceDao iDeviceMediaPadFaceDao;  //平板人脸识别多媒体服务设备信息持久层对象

    /**
     * <desc>
     *      根据条件projectId和deviceUnique获取云对讲设备类型
     * </desc>
     *
     * @param projectId    项目id
     * @param deviceUnique 设备序列号
     * @return 云对讲类型
     * @author wangzhi
     * @createDate 2018/05/22
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer getCloudIntercomByProjectIdAndDeviceUnique(String projectId, String deviceUnique) throws Exception {
        return iCloudTalkSDKMediaDao.getCloudIntercomByProjectIdAndDeviceUnique(projectId,deviceUnique);
    }

    /**
     * <desc>
     *      根据条件projectId和mediaId查询多媒体资源mediaId，用于验证多媒体资源是否存在
     * </desc>
     *
     * @param projectId 项目id
     * @param mediaId   多媒体资源id
     * @return 多媒体资源id
     * @author wangzhi
     * @createDate 2018/05/22
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public String getMediaIdByProjectIdAndMediaId(String projectId, String mediaId) throws Exception {
        return iCloudTalkSDKMediaDao.getMediaIdByProjectIdAndMediaId(projectId,mediaId);
    }

    /**
     * <desc>
     *      保存多媒体资源
     * </desc>
     *
     * @param cloudTalkSDKMediaSaveDTOS 待保存的数据集
     * @return
     * @author wangzhi
     * @createDate 2018/05/22
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public List<CloudTalkSDKMediaSaveOrUpdateDTO> saveMedia(List<CloudTalkSDKMediaSaveOrUpdateDTO> cloudTalkSDKMediaSaveDTOS) throws Exception {
        int intRes = 0;
        List<Map<String,Object>> batchParams = new ArrayList<>();
        List<Map<String,Object>> batchParamsForDevice = new ArrayList<>();
        Date currentTime = new Date();
        for (CloudTalkSDKMediaSaveOrUpdateDTO cloudTalkSDKMediaSaveDTO:cloudTalkSDKMediaSaveDTOS) {
            String mediaId = LogicIdUtil.bussinessId();
            DeviceMediaInfoPO deviceMediaInfoPO = new DeviceMediaInfoPO();
            BeanUtils.copyProperties(cloudTalkSDKMediaSaveDTO,deviceMediaInfoPO);
            deviceMediaInfoPO.setMediaId(mediaId);
            cloudTalkSDKMediaSaveDTO.setMediaId(mediaId);
            deviceMediaInfoPO.setCreateTime(currentTime);
            deviceMediaInfoPO.setUpdateTime(currentTime);
            batchParams.add(SqlUtil.durableData(deviceMediaInfoPO, PlatformConstants.TABLE_SAVE));
            if (null != cloudTalkSDKMediaSaveDTO.getBindDeviceGateInfo() && !cloudTalkSDKMediaSaveDTO.getBindDeviceGateInfo().isEmpty()){
                batchParamsForDevice.clear();
                for (CloudTalkSDKDeviceMediaBindDTO cloudTalkSDKDeviceMediaBindDTO:cloudTalkSDKMediaSaveDTO.getBindDeviceGateInfo()){
                    DeviceMediaGatePO deviceMediaGatePO = new DeviceMediaGatePO();
                    deviceMediaGatePO.setMediaId(mediaId);
                    deviceMediaGatePO.setProjectId(deviceMediaInfoPO.getProjectId());
                    deviceMediaGatePO.setDeviceUnique(cloudTalkSDKDeviceMediaBindDTO.getDeviceUnique());
                    deviceMediaGatePO.setCreateTime(currentTime);
                    deviceMediaGatePO.setUpdateTime(currentTime);
                    deviceMediaGatePO.setStatus(DataStatusEnum.NORMAL.getType());
                    batchParamsForDevice.add(SqlUtil.durableData(deviceMediaGatePO, PlatformConstants.TABLE_SAVE));
                }
                intRes += iCloudTalkSDKMediaDao.batchSaveDeviceMediaGate(batchParamsForDevice);
            }
           if (null != cloudTalkSDKMediaSaveDTO.getBindDeviceWallInfo() && !cloudTalkSDKMediaSaveDTO.getBindDeviceWallInfo().isEmpty()){
               batchParamsForDevice.clear();
               for (CloudTalkSDKDeviceMediaBindDTO cloudTalkSDKDeviceMediaBindDTO:cloudTalkSDKMediaSaveDTO.getBindDeviceWallInfo()){
                   DeviceMediaWallPO deviceMediaWallPO = new DeviceMediaWallPO();
                   deviceMediaWallPO.setMediaId(mediaId);
                   deviceMediaWallPO.setProjectId(deviceMediaInfoPO.getProjectId());
                   deviceMediaWallPO.setDeviceUnique(cloudTalkSDKDeviceMediaBindDTO.getDeviceUnique());
                   deviceMediaWallPO.setSn(cloudTalkSDKDeviceMediaBindDTO.getSn());
                   deviceMediaWallPO.setCreateTime(currentTime);
                   deviceMediaWallPO.setUpdateTime(currentTime);
                   deviceMediaWallPO.setStatus(DataStatusEnum.NORMAL.getType());
                   batchParamsForDevice.add(SqlUtil.durableData(deviceMediaWallPO, PlatformConstants.TABLE_SAVE));
               }
               intRes += iCloudTalkSDKMediaDao.batchSaveDeviceMediaWall(batchParamsForDevice);
           }

            if (null != cloudTalkSDKMediaSaveDTO.getBindPadFaceInfo() && !cloudTalkSDKMediaSaveDTO.getBindPadFaceInfo().isEmpty()){
                // 批量保存多媒体资源-人脸识别设备关联信息
                batchParamsForDevice.clear();
                for (CloudTalkSDKDeviceMediaBindDTO deviceMediaBindPadFaceDTO:cloudTalkSDKMediaSaveDTO.getBindPadFaceInfo()){
                    DeviceMediaPadFaceRecognitionPO deviceMediaPadFaceRecognitionPO = new DeviceMediaPadFaceRecognitionPO();
                    deviceMediaPadFaceRecognitionPO.setMediaId(deviceMediaInfoPO.getMediaId());
                    deviceMediaPadFaceRecognitionPO.setProjectId(deviceMediaInfoPO.getProjectId());
                    deviceMediaPadFaceRecognitionPO.setDeviceUnique(deviceMediaBindPadFaceDTO.getDeviceUnique());
                    deviceMediaPadFaceRecognitionPO.setCreateTime(deviceMediaInfoPO.getCreateTime());
                    deviceMediaPadFaceRecognitionPO.setUpdateTime(deviceMediaInfoPO.getCreateTime());
                    deviceMediaPadFaceRecognitionPO.setStatus(DataStatusEnum.NORMAL.getType());
                    batchParamsForDevice.add(SqlUtil.durableData(deviceMediaPadFaceRecognitionPO,PlatformConstants.TABLE_SAVE));
                }
                intRes += iDeviceMediaPadFaceDao.batchSave(batchParamsForDevice);
            }
        }
        intRes += iCloudTalkSDKMediaDao.batchSaveDeviceMediaInfo(batchParams);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("projectId",cloudTalkSDKMediaSaveDTOS.get(0).getProjectId());
        DeviceBusinessChangeLogPO deviceBusinessChangeLogPO
                = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_MEDIA,jsonObject,cloudTalkSDKMediaSaveDTOS.get(0).getProjectId());
        List<DeviceBusinessChangeLogPO> deviceBusinessChangeLogPOS = new ArrayList<>();
        deviceBusinessChangeLogPOS.add(deviceBusinessChangeLogPO);
        JSONObject dataJs = new JSONObject();
        dataJs.put("data",deviceBusinessChangeLogPOS);
        messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                JsonUtil.toJSON(dataJs), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);

        return cloudTalkSDKMediaSaveDTOS;
    }

    /**
     * <desc>
     *      更新多媒体资源
     * </desc>
     *
     * @param cloudTalkSDKMediaUpdateDTOS 待更新的数据集
     * @return
     * @author wangzhi
     * @createDate 2018/05/22
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public List<CloudTalkSDKMediaSaveOrUpdateDTO> updateMedia(List<CloudTalkSDKMediaSaveOrUpdateDTO> cloudTalkSDKMediaUpdateDTOS) throws Exception {
        int intRes = 0;
        List<Map<String,Object>> batchParams = new ArrayList<>();
        List<Map<String,Object>> batchParamsForDevice = new ArrayList<>();
        Date currentTime = new Date();
        for (CloudTalkSDKMediaSaveOrUpdateDTO cloudTalkSDKMediaUpdateDTO:cloudTalkSDKMediaUpdateDTOS){
            DeviceMediaInfoPO deviceMediaInfoPO = new DeviceMediaInfoPO();
            BeanUtils.copyProperties(cloudTalkSDKMediaUpdateDTO,deviceMediaInfoPO);
            String projectId = deviceMediaInfoPO.getProjectId();
            deviceMediaInfoPO.setProjectId(null);
            deviceMediaInfoPO.setUpdateTime(currentTime);
            batchParams.add(SqlUtil.durableData(deviceMediaInfoPO, PlatformConstants.TABLE_UPDATE));
            if (null != cloudTalkSDKMediaUpdateDTO.getBindDeviceGateInfo() && !cloudTalkSDKMediaUpdateDTO.getBindDeviceGateInfo().isEmpty()){
                batchParamsForDevice.clear();
                iCloudTalkSDKMediaDao.removeDeviceMediaGateByMediaId(deviceMediaInfoPO.getMediaId());
                for (CloudTalkSDKDeviceMediaBindDTO cloudTalkSDKDeviceMediaBindDTO:cloudTalkSDKMediaUpdateDTO.getBindDeviceGateInfo()){
                    DeviceMediaGatePO deviceMediaGatePO = new DeviceMediaGatePO();
                    deviceMediaGatePO.setMediaId(deviceMediaInfoPO.getMediaId());
                    deviceMediaGatePO.setProjectId(projectId);
                    deviceMediaGatePO.setDeviceUnique(cloudTalkSDKDeviceMediaBindDTO.getDeviceUnique());
                    deviceMediaGatePO.setCreateTime(currentTime);
                    deviceMediaGatePO.setUpdateTime(currentTime);
                    deviceMediaGatePO.setStatus(DataStatusEnum.NORMAL.getType());
                    batchParamsForDevice.add(SqlUtil.durableData(deviceMediaGatePO, PlatformConstants.TABLE_SAVE));
                }
                intRes += iCloudTalkSDKMediaDao.batchSaveDeviceMediaGate(batchParamsForDevice);
            }
            if (null != cloudTalkSDKMediaUpdateDTO.getBindDeviceWallInfo() && !cloudTalkSDKMediaUpdateDTO.getBindDeviceWallInfo().isEmpty()){
                batchParamsForDevice.clear();
                iCloudTalkSDKMediaDao.removeDeviceMediaWallByMediaId(deviceMediaInfoPO.getMediaId());
                for (CloudTalkSDKDeviceMediaBindDTO cloudTalkSDKDeviceMediaBindDTO:cloudTalkSDKMediaUpdateDTO.getBindDeviceWallInfo()){
                    DeviceMediaWallPO deviceMediaWallPO = new DeviceMediaWallPO();
                    deviceMediaWallPO.setMediaId(deviceMediaInfoPO.getMediaId());
                    deviceMediaWallPO.setProjectId(projectId);
                    deviceMediaWallPO.setDeviceUnique(cloudTalkSDKDeviceMediaBindDTO.getDeviceUnique());
                    deviceMediaWallPO.setSn(cloudTalkSDKDeviceMediaBindDTO.getSn());
                    deviceMediaWallPO.setCreateTime(currentTime);
                    deviceMediaWallPO.setUpdateTime(currentTime);
                    deviceMediaWallPO.setStatus(DataStatusEnum.NORMAL.getType());
                    batchParamsForDevice.add(SqlUtil.durableData(deviceMediaWallPO, PlatformConstants.TABLE_SAVE));
                }
                intRes += iCloudTalkSDKMediaDao.batchSaveDeviceMediaWall(batchParamsForDevice);
            }
        }
        iCloudTalkSDKMediaDao.batchUpdateDeviceMediaInfo(batchParams);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("projectId",cloudTalkSDKMediaUpdateDTOS.get(0).getProjectId());
        DeviceBusinessChangeLogPO deviceBusinessChangeLogPO
                = new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_MEDIA,jsonObject,cloudTalkSDKMediaUpdateDTOS.get(0).getProjectId());
        List<DeviceBusinessChangeLogPO> deviceBusinessChangeLogPOS = new ArrayList<>();
        deviceBusinessChangeLogPOS.add(deviceBusinessChangeLogPO);
        JSONObject dataJs = new JSONObject();
        dataJs.put("data",deviceBusinessChangeLogPOS);
        messageSender.send(RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                JsonUtil.toJSON(dataJs), RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY);

        return cloudTalkSDKMediaUpdateDTOS;
    }
}
